//
//  AppDelegate.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/23.
//  Copyright © 2018年 四川中农. All rights reserved.
//

enum PayResultType {
    case order // 订单支付
    case recharge // 余额支付不足
}

import UIKit
import IQKeyboardManagerSwift



@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    var type = PayResultType.order
    
    var tabbarCtrl:MyTabbarCobntroller!
    
    var isShowLogin = false

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        self.window = UIWindow.init(frame: UIScreen.main.bounds)
        
        if UserDefaults.standard.object(forKey: "isFirstOpen") != nil {
            self.addClildCtrl()
        }else{
            UserDefaults.standard.set("isFirstOpen", forKey: "isFirstOpen")
            UserDefaults.standard.synchronize()
            // 引导页
            let ctrl = GuidePageViewController()
            self.window?.rootViewController = ctrl
        }
        
        self.window?.makeKeyAndVisible()
        
        self.keyBoardManagerConfiguratiom()
        
        WXApi.registerApp("wx254f7df4de5262a6")
        
//        UITextField.appearance().setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        
        return WXApi.handleOpen(url, delegate: self)
    }
    
//    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
//        if url.host == "safepay" {
//            AlipaySDK.defaultService().processOrder(withPaymentResult: url) { (resultDic) in
//                print(resultDic!)
//                let returnCode = (resultDic! as NSDictionary)["resultStatus"] as! String
//                if returnCode == "9000" {
//                    self.noticeOnlyText("支付成功啦~")
//                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "payResult"), object: nil)
//                }else{
//                    self.noticeOnlyText("支付失败")
//                }
//            }
//            return true
//        }
//        return true
//    }
    
    // MARK: 9.0 以后回调
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        if url.host == "safepay" {
            AlipaySDK.defaultService().processOrder(withPaymentResult: url) { (resultDic) in
                print(resultDic!)
                let returnCode = (resultDic! as NSDictionary)["resultStatus"] as! String
                if returnCode == "9000" {
                    self.checkPayResult(isSuccess: true)
                }else{
                    self.checkPayResult(isSuccess: false)
                }
            }
            return true
        }
        return WXApi.handleOpen(url, delegate: self)
    }


}

extension AppDelegate:UITabBarControllerDelegate {
    
    func addClildCtrl(){
        self.isShowLogin = false
        self.tabbarCtrl = MyTabbarCobntroller()
        let homePageNav = self.setNavigationController(ctrl:Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "HomePageController"), title: "首页", normalImg: "daohang_homepage_2", selectedImg: "daohang_homepage_1")
        let classifyNav = self.setNavigationController(ctrl:Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ClassifyViewController"), title: "分类", normalImg: "daohang_fenlei_2", selectedImg: "daohang_fenlei_1")
        let shoppingCartNav = setNavigationController(ctrl: Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ShoppingCartViewController"), title: "购物车", normalImg: "daohang_gwc_2", selectedImg: "daohang_gwc_1")
        let myNav = setNavigationController(ctrl: Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "UserCenterViewController"), title: "我的", normalImg: "daohang_mine_2", selectedImg: "daohang_mine_1")
        
        self.tabbarCtrl.viewControllers = [homePageNav,classifyNav,shoppingCartNav,myNav]
        
        self.window?.rootViewController = self.tabbarCtrl
    }
    
    func setNavigationController(ctrl:UIViewController,title:String,normalImg:String,selectedImg:String)->UINavigationController{
        let nav = UINavigationController.init(rootViewController: ctrl)
        nav.tabBarItem.title = title
        nav.tabBarItem.image = UIImage.init(named: normalImg)?.withRenderingMode(.alwaysOriginal)
        nav.tabBarItem.selectedImage = UIImage.init(named: selectedImg)?.withRenderingMode(.alwaysOriginal)
        nav.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#f7c201")], for: .selected)
        nav.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 10)], for: .normal)
        return nav
    }
    
    private func keyBoardManagerConfiguratiom(){
        let keyBManager = IQKeyboardManager.shared
        keyBManager.enable = true
        keyBManager.shouldResignOnTouchOutside = true
        keyBManager.shouldShowToolbarPlaceholder = true
        keyBManager.toolbarDoneBarButtonItemText = "完成"
        keyBManager.enableAutoToolbar = true
        keyBManager.toolbarManageBehaviour = .byPosition
    }
}

extension AppDelegate:WXApiDelegate {
    func onResp(_ resp: BaseResp!) {
        if resp is PayResp {
            switch resp.errCode {
            case 0 :
                self.checkPayResult(isSuccess: true)
            default:
                self.checkPayResult(isSuccess: false)
                print("retcode = (resp.errCode), retstr = (resp.errStr)")
            }
        }
    }
}

extension AppDelegate {
    func checkPayResult(isSuccess:Bool){
        switch self.type {
        case .order:
            NotificationCenter.default.post(name: NSNotification.Name(rawValue:"payResult"), object: ["isSuccess":isSuccess])
        case .recharge:
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "rechargeResult"), object: ["isSuccess":isSuccess])
        }
    }
}























